<?php
/**
 * 代码原文链接： https://mp.weixin.qq.com/s?__biz=MzIxODQyNTU1MA==&amp;mid=2247484205&amp;idx=1&amp;sn=581b25d1d95fa0d48c90469aecdc638a&amp;chksm=97ebf28ca09c7b9acbdd491c40c0bef1741cdd581866b2449867208c42dba6ca95f29d296daa&amp;scene=27&key=&ascene=1&uin=&devicetype=iMac+MacBookPro15%2C2+OSX+OSX+12.2.1+build(21D62)&version=13080712&nettype=WIFI&lang=zh_CN&countrycode=CN&fontScale=100
 */
class Context
{
    private $state;
    public function SetState(State $state): void
    {
        $this->state = $state;
    }
    public function Request(): void
    {
        $this->state = $this->state->Handle();
    }
}

interface State
{
    public function Handle(): State;
}

class ConcreteStateA implements State
{
    public function Handle(): State
    {
        echo '当前是A状态', PHP_EOL;
        return new ConcreteStateB();
    }
}

class ConcreteStateB implements State
{
    public function Handle(): State
    {
        echo '当前是B状态', PHP_EOL;
        return new ConcreteStateA();
    }
}

$c = new Context();
$stateA = new ConcreteStateA();
$c->SetState($stateA);
$c->Request();
$c->Request();
$c->Request();
$c->Request();
